/*
 *  Copyright 2020-2021 Li Fei
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.pengshun.modules.api.coal.service.impl;

import com.pengshun.modules.api.coal.domain.Coal;
import com.pengshun.modules.api.coal.domain.CoalRecord;
import com.pengshun.modules.api.coal.service.dto.CoalInfoDto;
import com.pengshun.modules.api.coal.service.dto.MerchantCoalDto;
import com.pengshun.modules.api.coal.service.dto.MerchantCoalInfoDto;
import com.pengshun.modules.api.mapper.PsCoalMapper;
import com.pengshun.modules.api.coal.para.CoalParam;
import com.pengshun.modules.api.coal.repository.CoalRepository;
import com.pengshun.modules.api.coal.result.*;
import com.pengshun.modules.api.coal.service.CoalService;
import com.pengshun.modules.api.coal.service.dto.CoalDto;
import com.pengshun.modules.api.coal.service.mapstruct.CoalMapper;
import com.pengshun.modules.api.mapper.SystemMapper;
import com.pengshun.modules.api.system.service.dto.Content;
import com.pengshun.modules.common.BaseResult;
import com.pengshun.modules.common.CoalStatus;
import com.pengshun.modules.api.coal.util.DateUitl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lifei
 * @date 2020-11-06
 **/
@Service
@RequiredArgsConstructor
public class CoalServiceImpl implements CoalService {

    private final CoalRepository coalRepository;
    private final CoalMapper coalMapper;
    private final PsCoalMapper cm;
    private final  SystemMapper systemMapper;

    @Override
    public BaseResult selectCoalPriceByMineMouthId(CoalParam param) throws Exception {
        List<CoalPriceEchartsResult> result = new ArrayList<>();
        if(param.getCoalId()==null){
            //判断商品为自己输入 没有coalId的情况
            return new BaseResult(0,result);
        }
        //查询颜色
        List<Content> colorList = systemMapper.selectBaseCategory("coal_color");
        //type =1 按月查询  type=2 按年查询每个季度的平均值 type=3 一年每个月的平均值
        if (param.getType() == null) {
            //查询最近30天的记录
            param.setType(30);
            result = weekDate(param, colorList);
        } else {
            List<CoalPriceDate> coalPriceDates = new ArrayList<>();
            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM");
            SimpleDateFormat format3 = new SimpleDateFormat("MM-dd");
            if (param.getType() == 1) {
                //查询指定年月数据
                coalPriceDates = cm.selectPriceByDateAndCoalId(param.getCoalId(), param.getDate());
                if (coalPriceDates.size() == 0) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy");
                    SimpleDateFormat format2 = new SimpleDateFormat("MM");

                    CoalPriceDate coalPrice = cm.selectReordByDate(param.getCoalId(), format1.format(param.getDate()));
                    if(coalPrice==null){
                        return  new BaseResult(0,result);
                    }
                    String date = format3.format(param.getDate());
                    coalPrice.setDay(date);
                    coalPrice.setDate(date);
                    coalPriceDates.add(coalPrice);
                    //如果日期小于当前月份 设置月底价格   查询当前月多少天
                    if (param.getDate().getTime() < format1.parse(format1.format(new Date())).getTime()) {
                        Calendar rightNow = Calendar.getInstance();
                        rightNow.setTime(param.getDate());
                        int days = rightNow.getActualMaximum(Calendar.DAY_OF_MONTH);
                        String dates = format2.format(param.getDate()) + "-" + days;
                        CoalPriceDate coalPrice1 = new CoalPriceDate(coalPrice.getCoalPrice(), dates);
                        coalPrice1.setDay(dates);
                        coalPriceDates.add(coalPrice1);
                    }
                    //如果等于 设置当天日期的价格
                    if (format1.format(param.getDate()).equals(format1.format(new Date())) &&
                            !format2.format(new Date()).equals("01")) {
                        String dates = format3.format(new Date());
                        CoalPriceDate coalPrice1 = new CoalPriceDate(coalPrice.getCoalPrice(), dates);
                        coalPrice1.setDay(dates);
                        coalPriceDates.add(coalPrice1);
                    }


                } else {
                    if (coalPriceDates.get(0).getMouth() != 1) {
                        CoalPriceDate coalPrice = cm.selectReordByDate(param.getCoalId(), coalPriceDates.get(0).getDay());
                        String date = coalPriceDates.get(0).getDate().split("-")[0] + "-01";
                        if (coalPrice != null) {
                            coalPrice.setDate(date);
                            coalPriceDates.add(0, coalPrice);
                        }
                    }
                }
                for(CoalPriceDate date:coalPriceDates){
                    date.setXdesc(date.getDate());
                }
            } else if (param.getType() == 2) {
                param.setDate(param.getDate() == null ? new Date() : param.getDate());
                //查询指定年 季度平均数据
                coalPriceDates = cm.selectPriceByjidu(param.getCoalId(), param.getDate());
                for(CoalPriceDate date:coalPriceDates){
                    if(date.getDate().equals("1")){
                        date.setDate("第一季度");
                        date.setXdesc("一季度");
                    }else
                    if(date.getDate().equals("2")){
                        date.setDate("第二季度");
                        date.setXdesc("二季度");
                    }else
                    if(date.getDate().equals("3")){
                        date.setDate("第三季度");
                        date.setXdesc("三季度");
                    }else {
                        date.setDate("第四季度");
                        date.setXdesc("四季度");
                    }

                }

            } else {
                param.setDate(param.getDate() == null ? new Date() : param.getDate());
                coalPriceDates = cm.selectPriceByYears(param.getCoalId(), param.getDate());
                if (coalPriceDates.size() == 0) {
                    CoalPriceDate coalPrice = cm.selectReordByDate(param.getCoalId(), format1.format(param.getDate()));
                    String date = format3.format(param.getDate());
                    coalPrice.setDay(date);
                    coalPrice.setDate(date);
                    coalPriceDates.add(coalPrice);
                } else {
                    //补月份数据

                    //设置每个月多余日期显示
                    Integer j = 1;
                    for (int i = 0; i < coalPriceDates.size(); i++) {
                        Integer num = Integer.parseInt(coalPriceDates.get(i).getXdesc());
                        if (j < num) {
                            j = num;
                        }
                        if (coalPriceDates.get(i).getXdesc().equals(j.toString())) {
                            j++;
                            coalPriceDates.get(i).setXdesc(coalPriceDates.get(i).getXdesc() + "月");
                        } else {

                            if (j - 1 == num) {
                                coalPriceDates.get(i).setXdesc("");
                            }
                        }
                    }
                }
            }
            CoalPriceEchartsResult coalPriceEchartsResult = new CoalPriceEchartsResult(colorList.get(0).getValue(), coalPriceDates);
            result.add(coalPriceEchartsResult);
        }

        //type =1 查询7天记录   type=2 查询一年记录
//        if (param.getType() == 30 || param.getType() == 90) {
//            result = weekDate(param, colorList);
//        }
//        if (param.getType() == 180 || param.getType() == 365) {
//            result = yearDate(param, colorList);
//        }
        return new BaseResult(0, result);

    }

    @Override
    public BaseResult selectCoalDetil(Long coalId) {
        CoalDto dto = cm.findCoalDetilById(coalId);

//        List<CoalInfoDto> coalInfoDtos = dto.getCoalInfos();
        List<CoalInfoDto> coalInfoDtos = new ArrayList<>();
        MerchantCoalDto coalInfoDto= new MerchantCoalDto();
        if (dto != null && dto.getCoalInfos().size() > 0) {

            coalInfoDto.setWholeWater(dto.getWholeWater());
            coalInfoDto.setAllSulphur(dto.getAllSulphur());
            coalInfoDto.setSerchHuifen(dto.getSerchHuifen());
            for (CoalInfoDto info : dto.getCoalInfos()) {
                if(info.getCoalName().equals("内水")){
                    coalInfoDto.setNsValue(info.getValue());
                }
                if(info.getCoalName().equals("空干基挥发")){
                    coalInfoDto.setKfValue(info.getValue());
                }
                if(info.getCoalName().equals("收到基挥发")){
                    coalInfoDto.setSfValue(info.getValue());
                }
                if(info.getCoalName().equals("干燥无灰基挥发")){
                    coalInfoDto.setGfValue(info.getValue());
                }
                if(info.getCoalName().equals("焦渣特征")){
                    coalInfoDto.setJzValue(info.getValue());
                }
                if(info.getCoalName().equals("固定碳")){
                    coalInfoDto.setGtValue(info.getValue());
                }
                if(info.getCoalName().equals("空干基高位")){
                    coalInfoDto.setKwValue(info.getValue());
                }
                if(info.getCoalName().equals("收到基低位")){
                    coalInfoDto.setSwValue(info.getValue());
                }
            }
        }
        coalInfoDtos.add(new CoalInfoDto("全水", coalInfoDto.getWholeWater(), "%"));
        coalInfoDtos.add(new CoalInfoDto("內水", coalInfoDto.getNsValue(), "%"));
        coalInfoDtos.add(new CoalInfoDto("干基灰分", coalInfoDto.getSerchHuifen(), "%"));
        coalInfoDtos.add(new CoalInfoDto("空干基挥发", coalInfoDto.getKfValue(), "%"));
        coalInfoDtos.add(new CoalInfoDto("收到基挥发", coalInfoDto.getSfValue(), "%"));
        coalInfoDtos.add(new CoalInfoDto("干燥无灰基挥发", coalInfoDto.getGfValue(), "%"));
        coalInfoDtos.add(new CoalInfoDto("含硫量", coalInfoDto.getAllSulphur(), "%"));
        coalInfoDtos.add(new CoalInfoDto("焦渣特征", coalInfoDto.getJzValue(), ""));
        coalInfoDtos.add(new CoalInfoDto("固定碳", coalInfoDto.getGtValue(), "%"));
        coalInfoDtos.add(new CoalInfoDto("空干基高位", coalInfoDto.getKwValue(), "kCal/kg"));
        coalInfoDtos.add(new CoalInfoDto("收到基低位", coalInfoDto.getSwValue(), "kCal/kg"));
        coalInfoDtos.add(new CoalInfoDto("--", null, null));
        dto.setCoalInfos(coalInfoDtos);
        for (CoalInfoDto merchantCoalInfo :dto.getCoalInfos()) {
            merchantCoalInfo.setValue(merchantCoalInfo.getValue() == null ? "--" : merchantCoalInfo.getValue());
            merchantCoalInfo.setUnit(merchantCoalInfo.getValue() == null||merchantCoalInfo.getValue().equals("") ? "--" : merchantCoalInfo.getUnit());
        }
        return new BaseResult(0, dto);
    }

    @Override
    public BaseResult selectCoalPriceByCoalId(CoalParam form) throws Exception {
        List<CoalPriceEchartsResult> results = new ArrayList<>();
        if (form.getType() == 1) {
            //查询年份平均值
            results = cm.selectLatelyYearByDate(form.getCoalId(), form.getStartDate(), form.getEndDate());
        }
        if (form.getType() == 2) {
            //查询月份平均值
            results = cm.selectLatelyYearData(form.getCoalId(), form.getStartDate(), form.getEndDate());

        }


        List<Content> colorList = systemMapper.selectBaseCategory("coal_color");
        //补全数据
        int i = 0, k = 0;
        String year[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};

        for (CoalPriceEchartsResult result : results) {
            if (i == colorList.size() - 1) {
                i = 0;
            }
            result.setColor(colorList.get(i).getValue());
            i++;
            for (CoalPriceDate date : result.getDates()) {
                date.setXdesc(form.getType() == 2?date.getDate()+"月": result.getCoalId()+"年");
            }
        }
        return new BaseResult(0, results);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult save(CoalDto form) throws Exception {
        form.setStatus(CoalStatus.TWO_STATUS);
        Coal res = coalRepository.save(coalMapper.toEntity(form));
        return new BaseResult(0, res);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult update(CoalDto form) throws Exception {
        Coal res = coalRepository.save(coalMapper.toEntity(form));
        return new BaseResult(0, res);
    }

    @Override
    public BaseResult selectCoalCode(CoalParam para) {
        List<CoalDto> dtos = coalMapper.toDto(cm.findBymineMouthId(para.getMineMouthId(), para.getCategoryCode()));
        return new BaseResult(0, dtos);
    }

    @Override
    public BaseResult selectCoalKline(CoalParam param) {
        List<CoalKLineResult> coalPriceDates = cm.selectCoalKline(param.getCoalId(), param.getDay());
        if (coalPriceDates.size() > 0&&coalPriceDates.get(0).getCoalPriceDates().size() > 0) {
            if (!coalPriceDates.get(0).getCoalPriceDates().get(0).getDay().equals("01")) {
                CoalRecord record = cm.selectOneBydate(param.getCoalId(), coalPriceDates.get(0).getCoalPriceDates().get(0).getDate());
                coalPriceDates.get(0).setStartPrice(record == null ? new BigDecimal(0) : record.getCoalPrice());
            }
        }
        //跳过设置第一个集合的值
        int i = 0;
        BigDecimal price = new BigDecimal(0);
        for (CoalKLineResult res : coalPriceDates) {
            //设置月底价
            res.setEndPrice(res.getCoalPriceDates().size() > 0 ? res.getCoalPriceDates().get(res.getCoalPriceDates().size() - 1).getCoalPrice() : null);
            BigDecimal max = new BigDecimal(0);
            BigDecimal min = new BigDecimal(99999999);
            BigDecimal avg = new BigDecimal(0);
            for (CoalPriceDate da : res.getCoalPriceDates()) {
                if (da.getCoalPrice().compareTo(max) == 1) {
                    max = da.getCoalPrice();
                }
                if (da.getCoalPrice().compareTo(min) == -1) {
                    min = da.getCoalPrice();
                }
                avg = avg.add(da.getCoalPrice());
            }
            BigDecimal avgs = new BigDecimal(res.getCoalPriceDates().size());
            BigDecimal avgs1 = avg.divide(avgs, 2, BigDecimal.ROUND_HALF_UP);
            res.setAvgPrice(avgs1);
            //设置最大值
            res.setMaxPrice(max);
            //设置最小值
            res.setMinPrice(min);
            //设置月初值
            if (i > 0 && !res.getCoalPriceDates().get(0).getDay().equals("01")) {
                res.setStartPrice(price);
            } else {
                res.setStartPrice(res.getCoalPriceDates().get(0).getCoalPrice());
            }
            price = res.getEndPrice();
            i++;

        }
        return new BaseResult(0, coalPriceDates);
    }

    @Override
    public BaseResult selectCoalBrokenLine(CoalParam form) {
        List<CoalPriceEchartsResult> results= cm.selectCoalBrokenLine(form.getCoalId(), form.getSDate(), form.getEDate());
        List<Content> colorList = systemMapper.selectBaseCategory("coal_color");
        for (CoalPriceEchartsResult result:results){
            result.setColor(colorList.get(0).getValue());
            for(CoalPriceDate date: result.getDates()){
                date.setXdesc(date.getDate());
            }
        }
        return new BaseResult(0,results);
    }

    @Override
    public BaseResult selectCoalCategory() {
        List<Content> coal = systemMapper.selectCoalCategory();
        return new BaseResult(0,coal);
    }


    private List<CoalPriceEchartsResult> weekDate(CoalParam param, List<Content> colorList) throws Exception {
        List<CoalPriceEchartsResult> results = new ArrayList<>();

        List<CoalPriceDate> coalPriceDates = cm.selectPriceByDayAndCoalId(param.getCoalId(), param.getType());
        //拿到最近7天日期集合
        List<String> dates = DateUitl.getDaysBetwwen(param.getType() - 1);
        //补全日期
        List<CoalPriceDate> dateList = new ArrayList<>();

        CoalDto coalDto = new CoalDto();
        if (coalPriceDates.size() == 0) {
            Coal coal = coalRepository.findById(param.getCoalId()).orElseGet(Coal::new);
            coalDto = coalMapper.toDto(coal);
        }
        for (String da : dates) {
            //标记是否存在  默认不存在
            Boolean isNotExtise = false;
            //如果煤炭记录集合为空  直接拿 父级 数据补全
            if (coalPriceDates.size() == 0) {
                CoalPriceDate date = new CoalPriceDate(coalDto.getCoalPrice(), coalDto.getPriceUnit(), da);
                dateList.add(date);
            } else {
                //如果煤炭记录集合不为空  将同等日期的值 赋予 用最近7天集合
                for (CoalPriceDate re : coalPriceDates) {
                    if (re.getDate().equals(da)) {
                        dateList.add(re);
                        isNotExtise = true;
                    }
                }
                if (!isNotExtise) {
                    CoalPriceDate date = new CoalPriceDate(da);
                    dateList.add(date);
                }
            }
        }

        //补全价格数据
        //标记是否第一个值
        int num = -1;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (coalPriceDates.size() == 0) {

//            List<Object[]> date1 = coalRecordRepository.selectReordByDate(param.getCoalId(), format.format(new Date()));
//            List<CoalPriceDate> dates1 = CastEntityUtil.castEntity(date1, CoalPriceDate.class);
            CoalPriceDate dates1 = cm.selectReordByDate(param.getCoalId(), format.format(new Date()));
            dateList.get(0).setCoalPrice(dates1.getCoalPrice());
            dateList.get(0).setPriceUnit(dates1.getPriceUnit());
            dateList.get(dateList.size() - 1).setCoalPrice(dates1.getCoalPrice());
            dateList.get(dateList.size() - 1).setPriceUnit(dates1.getPriceUnit());
            coalPriceDates = dateList;
        } else {
            for (CoalPriceDate re : coalPriceDates) {
                if (re.getCoalPrice() == null) {
                    if (num == -1) {
                        //如果第一条记录 价格为空 则 查询 当前日期以前的最近一条记录
                        CoalPriceDate dates1 = cm.selectReordByDate(param.getCoalId(), format.format(new Date()));
                        if (dates.size() > 0) {
                            re.setCoalPrice(dates1.getCoalPrice());
                            re.setPriceUnit(dates1.getPriceUnit());
                        }
                    } else {
                        re.setCoalPrice(coalPriceDates.get(num).getCoalPrice());
                        re.setPriceUnit(coalPriceDates.get(num).getPriceUnit());
                    }
                }
                num++;
            }
        }
        CoalPriceEchartsResult coalPriceEchartsResult = new CoalPriceEchartsResult(colorList.get(0).getValue(), coalPriceDates);
        results.add(coalPriceEchartsResult);
        return results;
    }

    private List<CoalPriceEchartsResult> yearDate(CoalParam param, List<Content> colorList) throws Exception {
        List<CoalPriceEchartsResult> results = new ArrayList<>();

        List<CoalPriceDate> list = cm.selectPriceByDayAndCoalId(param.getCoalId(), param.getType());
        CoalPriceEchartsResult coalPriceEchartsResult = new CoalPriceEchartsResult(colorList.get(0).getValue(), list);
        results.add(coalPriceEchartsResult);
        return results;
        //拿到最近12个月的 日期集合
//        List<String> dates = DateUitl.getMounths();

        //补全日期
//        for (CoalPriceDate cp : list) {
//            List<CoalPriceDate> dateList = new ArrayList<>();

//            for (String da : dates) {
//                //标记是否存在  默认不存在
//                Boolean isNotExtise = false;
//                //如果煤炭记录集合为空  直接拿 父级 数据补全
//                if (cp.getDates().size() == 0) {
//                    CoalPriceDate date = new CoalPriceDate(cp.getPrice(), cp.getUnit(), da);
//                    dateList.add(date);
//                } else {
//                    //如果煤炭记录集合不为空  将同等日期的值 赋予 用最近7天集合
//                    for (CoalPriceDate re : cp.getDates()) {
//                        if (re.getDate().equals(da)) {
//                            dateList.add(re);
//                            isNotExtise = true;
//                        }
//                    }
//                    if (!isNotExtise) {
//                        CoalPriceDate date = new CoalPriceDate(da);
//                        dateList.add(date);
//                    }
//                }
//            }
//            cp.setDates(dateList);
//        }

        //补全价格数据
//        int colorIndex = 0;
//        for (CoalPriceEchartsResult cp : list) {
//            //标记是否第一个值
//            int num = -1;
//            //颜色赋值  如果num和颜色集合大小一样  则重新从0取值赋值
//            if (num <= colorList.size()) {
//                cp.setColor(colorList.get(colorIndex).getValue());
//            } else {
//                colorIndex = 0;
//            }
//            colorIndex++;
//            for (CoalPriceDate re : cp.getDates()) {
//                if (re.getCoalPrice() == null) {
//                    if (num == -1) {
//                        //如果第一条记录 价格为空 则 查询 当前日期以前的最近一条记录
//                        List<Object[]> date1 = coalRecordRepository.selectReordByMounth(cp.getCoalId(), re.getDate());
//                        List<CoalPriceDate> dates1 = CastEntityUtil.castEntity(date1, CoalPriceDate.class);
//                        if (dates.size() > 0) {
//                            re.setCoalPrice(dates1.get(0).getCoalPrice());
//                            re.setPriceUnit(dates1.get(0).getPriceUnit());
//                        }
//                    } else {
//                        re.setCoalPrice(cp.getDates().get(num).getCoalPrice());
//                        re.setPriceUnit(cp.getDates().get(num).getPriceUnit());
//                    }
//                }
//                num++;
//            }
//
//        }
//        return list;
    }
}